package com.xqy.wexmini.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xqy.wexmini.VO.DiscussVO;
import com.xqy.wexmini.VO.DiscussuserVO;
import com.xqy.wexmini.common.R;
import com.xqy.wexmini.common.ResponseResult;
import com.xqy.wexmini.domain.Discuss;
import com.xqy.wexmini.domain.Discusspraise;
import com.xqy.wexmini.domain.Discussuser;
import com.xqy.wexmini.form.DiscussForm;
import com.xqy.wexmini.form.DiscussUserForm;
import com.xqy.wexmini.form.DiscusspraiseForm;
import com.xqy.wexmini.mapper.DiscusspraiseMapper;
import com.xqy.wexmini.mapper.DiscussuserMapper;
import com.xqy.wexmini.service.DiscussService;
import com.xqy.wexmini.service.DiscusspraiseService;
import com.xqy.wexmini.service.DiscussuserService;
import com.xqy.wexmini.service.UserService;
import com.xqy.wexmini.utils.JwtTokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 讨论区 前端控制器
 * </p>
 *
 * @author xia
 * @since 2022-05-28
 */
@Api(tags = "论坛")
@RestController
@RequestMapping(value = "/discuss")
public class DiscussController {
    @Autowired
    private DiscussService discussService;
    @Autowired
    private DiscussuserService discussuserService;
    @Autowired
    private DiscusspraiseService discusspraiseService;
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    private DiscussController discussController;
    @Autowired
    private DiscusspraiseMapper discusspraiseMapper;
    @Autowired
    private DiscussuserMapper discussuserMapper;
    @Autowired
    private UserService userService;

    @ApiOperation("查询所有讨论主题")
    @GetMapping(value = "/selectAll/{current}/{limit}")
    public R Select(@PathVariable Long current, @PathVariable Long limit,HttpServletRequest httpServletRequest){
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        Page<Discuss> page = new Page<>();
        page.setCurrent(current);
        page.setSize(limit);
        QueryWrapper<Discuss> queryWrapper = new QueryWrapper<>();
        //排序
        queryWrapper.orderByAsc("id");

        discussService.page(page,queryWrapper);
        long total = page.getTotal();


        //给每条数据增加一个字段：判断用户给该文章是否点赞,并且添加讨论字段
        List<DiscussVO> adc = discussController.adc(openId, page.getRecords());


        return R.ok().put("total",total).put("raw",adc);
    }

    @ApiOperation("查询特定主题下的讨论")
    @GetMapping(value = "/selectOne/{current}/{limit}")
    public R Select1(@PathVariable Long current, @PathVariable Long limit,Long id){
        Page<Discussuser> page = new Page<>(current, limit);
        QueryWrapper<Discussuser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Discussuser::getDiscussId,id);
        //排序
        queryWrapper.orderByAsc("id");
        discussuserService.page(page,queryWrapper);
        long total = page.getTotal();
        List<DiscussuserVO> list=new ArrayList<>();
        DiscussuserVO discussVO=new DiscussuserVO();
        for (Discussuser record : page.getRecords()) {
            BeanUtils.copyProperties(record,discussVO);
            discussVO.setAvatarUrl(userService.selectAvatar(record.getUserName()));
            discussVO.setNickName(userService.selectNickName(record.getUserName()));
            list.add(discussVO);
        }
        return R.ok().put("total",total).put("raw",list);
    }
    @ApiOperation("根据类型查询")
    @GetMapping(value = "/selectByType/{current}/{limit}")
    public R Select2(@PathVariable Long current,@PathVariable Long limit, String type,HttpServletRequest httpServletRequest){
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        Page<Discuss> page = new Page<>();
        page.setCurrent(current);
        page.setSize(limit);
        QueryWrapper<Discuss> queryWrapper = new QueryWrapper<>();
        //排序
        queryWrapper.orderByAsc("id");
        queryWrapper.lambda().eq(Discuss::getType,type);
        discussService.page(page,queryWrapper);
        long total = page.getTotal();
        List<DiscussVO> adc = discussController.adc(openId, page.getRecords());

        return R.ok().put("total",total).put("raw",adc);
    }

    public List<DiscussVO> adc(String openId,List<Discuss> list2){
        List<DiscussVO> list=new ArrayList<>();

        //给每条数据增加一个字段：判断用户给该文章是否点赞
        for(Discuss discuss : list2){
            DiscussVO discussVO=new DiscussVO();
            Integer id = discuss.getId();
            Discusspraise one = discusspraiseService.getOne(new LambdaQueryWrapper<Discusspraise>().eq(Discusspraise::getDiscussId,
                    discuss.getId()).eq(Discusspraise::getUserName, openId));
            BeanUtils.copyProperties(discuss,discussVO);
            discussVO.setDiscussNum(discussuserService.getIdnums(id));
            if(one!=null){
                discussVO.setIspraise(true);//已经点赞，可以取消点赞
            }else{
                discussVO.setIspraise(false);//未点赞，可以取消点赞
            }

            list.add(discussVO);
        }
        return list;
    }
    @ApiOperation("发布主题")
    @PostMapping(value = "/add")
    public R Select2(@RequestBody DiscussForm discussesForm, HttpServletRequest httpServletRequest){
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        discussesForm.setUserName(openId);
        Discuss discusses=new Discuss();
        BeanUtils.copyProperties(discussesForm,discusses);
        discusses.setAvatarUrl(userService.selectAvatar(openId));
        discusses.setNickName(userService.selectNickName(openId));
        boolean save = discussService.save(discusses);
        if(!save){
            try {
                throw new Exception("数据库异常");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.ok();
    }
    @ApiOperation("通过id删除讨论")
    @DeleteMapping(value = "/delete")
    public R delete(Long id,HttpServletRequest httpServletRequest){
        boolean b = discussuserService.removeById(id);
        Discussuser one = discussuserService.getOne(new LambdaQueryWrapper<Discussuser>().eq(Discussuser::getId, id));
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        String userName = one.getUserName();
        if(!openId.equals(userName)){
            return R.error("权限不够,只能自己删除自己的评论");
        }
        if(!b){
            try {
                throw new Exception("删除异常");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.ok();
    }
    @ApiOperation("通过id删除主题")
    @DeleteMapping(value = "/delete1")
    public R delete1(Long id,HttpServletRequest httpServletRequest){
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        String userName = discussService.getOne(new LambdaQueryWrapper<Discuss>().eq(Discuss::getId, id)).getUserName();
        if(!openId.equals(userName)){
            return R.error("权限不够，只能删除自己的主题");
        }
        List<Discussuser> processes = discussuserService.list(new QueryWrapper<Discussuser>().lambda()
                .eq(Discussuser::getDiscussId, id));
        for(Discussuser discussuser:processes){
            discussuserService.removeById(discussuser.getId());
        }
        boolean b = discussService.removeById(id);
        if(!b){
            try {
                throw new Exception("删除异常");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.ok();
    }
    @ApiOperation("发布评论")
    @GetMapping(value = "/addDiscuss")
    public R add(DiscussUserForm discussUserForm,HttpServletRequest httpServletRequest){
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        Discussuser discussuser=new Discussuser();
        BeanUtils.copyProperties(discussUserForm,discussuser);
        discussuser.setUserName(openId);
        boolean save = discussuserService.save(discussuser);
        if(!save){
            try {
                throw new Exception("数据库异常");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.ok();
    }
    @ApiOperation("用户点赞")
    @PostMapping(value = "/praise")
    public R dian(@RequestBody DiscusspraiseForm discusspraiseForm,HttpServletRequest httpServletRequest){
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        discusspraiseForm.setUserName(openId);
        Integer discussId = discusspraiseForm.getDiscussId();
        Discuss byId = discussService.getById(discussId);
        Integer praise = byId.getPraise();
        byId.setPraise(++praise);
        discussService.updateById(byId);
        Discusspraise discusspraise=new Discusspraise();
        BeanUtils.copyProperties(discusspraiseForm,discusspraise);
        discusspraise.setUserName(openId);
        Discuss one = discussService.getOne(new LambdaQueryWrapper<Discuss>().eq(Discuss::getId, discussId));
        discusspraise.setDiscussUser(one.getUserName());
        boolean b = discusspraiseService.save(discusspraise);
        if(!b){
            try {
                throw new Exception("删除异常");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.ok();
    }
    @ApiOperation("用户取消点赞")
    @DeleteMapping(value = "/praise1")
    public R delete1(DiscusspraiseForm discusspraiseForm,HttpServletRequest httpServletRequest){
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        discusspraiseForm.setUserName(openId);
        List<Discusspraise> discusspraises = discusspraiseService.list(new QueryWrapper<Discusspraise>().lambda()
                .eq(Discusspraise::getUserName, discusspraiseForm.getUserName())
                .eq(Discusspraise::getDiscussId,discusspraiseForm.getDiscussId())
        );
        Discuss byId = discussService.getById(discusspraiseForm.getDiscussId());
        Integer praise = byId.getPraise();
        byId.setPraise(--praise);
        discussService.updateById(byId);
        boolean b = discusspraiseService.removeById(discusspraises.get(0).getId());
        if(!b){
            try {
                throw new Exception("删除异常");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.ok();
    }
    @ApiOperation("查询自己发表的论坛文章")
    @PostMapping(value = "/MyArticle")
    public ResponseResult selectMy(HttpServletRequest httpServletRequest){
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        List<Discuss> list = discussService.list(new LambdaQueryWrapper<Discuss>().eq(Discuss::getUserName, openId));
        return new ResponseResult(200,list);
    }

    @ApiOperation("自己获得点赞量")
    @PostMapping(value = "/MyPraise")
    public ResponseResult selectMydianzan(HttpServletRequest httpServletRequest){
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        Integer count = discusspraiseMapper.selectCount(new LambdaQueryWrapper<Discusspraise>().eq(Discusspraise::getDiscussUser, openId));
        return new ResponseResult(200,count);
    }

    @ApiOperation("自己评论数量")
    @PostMapping(value = "/MyComments")
    public ResponseResult selectMyComments(HttpServletRequest httpServletRequest){
        String openId = jwtTokenUtils.getOpenId(httpServletRequest);
        Integer count = discussuserMapper.selectCount(new LambdaQueryWrapper<Discussuser>().eq(Discussuser::getUserName, openId));
        return new ResponseResult(200,count);
    }
}
